#!/usr/bin/env python3
"""
搜索工具集
"""

import requests
import json
from typing import Dict, Any, List
from ..core.tool import Tool, ToolResult

class GoogleSearchTool(Tool):
    """Google搜索工具"""
    
    def __init__(self, api_key: str = None, search_engine_id: str = None):
        super().__init__(
            name="google_search",
            description="Google搜索服务：搜索网络信息"
        )
        self.api_key = api_key
        self.search_engine_id = search_engine_id
        self.base_url = "https://www.googleapis.com/customsearch/v1"
    
    def execute(self, query: str, num_results: int = 5, **kwargs) -> ToolResult:
        """执行Google搜索"""
        try:
            if not self.api_key or not self.search_engine_id:
                return ToolResult(
                    success=False,
                    error="Google API密钥或搜索引擎ID未配置"
                )
            
            params = {
                "key": self.api_key,
                "cx": self.search_engine_id,
                "q": query,
                "num": min(num_results, 10)
            }
            
            response = requests.get(self.base_url, params=params, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            
            if "items" in data:
                results = []
                for item in data["items"]:
                    result = {
                        "title": item.get("title", ""),
                        "link": item.get("link", ""),
                        "snippet": item.get("snippet", ""),
                        "display_link": item.get("displayLink", "")
                    }
                    results.append(result)
                
                return ToolResult(
                    success=True,
                    data={
                        "query": query,
                        "total_results": data.get("searchInformation", {}).get("totalResults", "0"),
                        "results": results
                    },
                    metadata={
                        "search_time": data.get("searchInformation", {}).get("searchTime", 0)
                    }
                )
            else:
                return ToolResult(
                    success=False,
                    error="未找到搜索结果"
                )
                
        except requests.exceptions.RequestException as e:
            return ToolResult(
                success=False,
                error=f"搜索请求失败: {str(e)}"
            )
        except Exception as e:
            return ToolResult(
                success=False,
                error=str(e)
            )
    
    def get_schema(self) -> Dict[str, Any]:
        """获取工具调用模式"""
        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "搜索查询关键词"
                        },
                        "num_results": {
                            "type": "integer",
                            "minimum": 1,
                            "maximum": 10,
                            "description": "返回结果数量"
                        }
                    },
                    "required": ["query"]
                }
            }
        }

class StackOverflowTool(Tool):
    """Stack Overflow搜索工具"""
    
    def __init__(self):
        super().__init__(
            name="stackoverflow_search",
            description="Stack Overflow搜索服务：搜索技术问题"
        )
        self.base_url = "https://api.stackexchange.com/2.3"
    
    def execute(self, query: str, tags: List[str] = None, **kwargs) -> ToolResult:
        """执行Stack Overflow搜索"""
        try:
            params = {
                "order": "desc",
                "sort": "relevance",
                "intitle": query,
                "site": "stackoverflow",
                "filter": "withbody",
                "pagesize": 5
            }
            
            if tags:
                params["tagged"] = ";".join(tags)
            
            response = requests.get(f"{self.base_url}/search/advanced", params=params, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            
            if "items" in data:
                questions = []
                for item in data["items"]:
                    question = {
                        "title": item.get("title", ""),
                        "link": item.get("link", ""),
                        "score": item.get("score", 0),
                        "answer_count": item.get("answer_count", 0),
                        "is_answered": item.get("is_answered", False),
                        "tags": item.get("tags", [])
                    }
                    questions.append(question)
                
                return ToolResult(
                    success=True,
                    data={
                        "query": query,
                        "total_questions": len(questions),
                        "questions": questions
                    }
                )
            else:
                return ToolResult(
                    success=False,
                    error="未找到相关问题"
                )
                
        except requests.exceptions.RequestException as e:
            return ToolResult(
                success=False,
                error=f"API请求失败: {str(e)}"
            )
        except Exception as e:
            return ToolResult(
                success=False,
                error=str(e)
            )
    
    def get_schema(self) -> Dict[str, Any]:
        """获取工具调用模式"""
        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "搜索查询关键词"
                        },
                        "tags": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "相关技术标签"
                        }
                    },
                    "required": ["query"]
                }
            }
        }

class GitHubSearchTool(Tool):
    """GitHub搜索工具"""
    
    def __init__(self, access_token: str = None):
        super().__init__(
            name="github_search",
            description="GitHub搜索服务：搜索代码和项目"
        )
        self.access_token = access_token
        self.base_url = "https://api.github.com"
        self.headers = {"Accept": "application/vnd.github.v3+json"}
        
        if access_token:
            self.headers["Authorization"] = f"token {access_token}"
    
    def execute(self, query: str, search_type: str = "code", **kwargs) -> ToolResult:
        """执行GitHub搜索"""
        try:
            params = {
                "q": query,
                "sort": "best-match",
                "per_page": 5
            }
            
            if search_type == "code":
                url = f"{self.base_url}/search/code"
            elif search_type == "repositories":
                url = f"{self.base_url}/search/repositories"
            elif search_type == "issues":
                url = f"{self.base_url}/search/issues"
            else:
                return ToolResult(
                    success=False,
                    error=f"不支持的搜索类型: {search_type}"
                )
            
            response = requests.get(url, headers=self.headers, params=params, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            
            if "items" in data:
                results = []
                for item in data["items"]:
                    if search_type == "code":
                        result = {
                            "name": item.get("name", ""),
                            "path": item.get("path", ""),
                            "repository": item.get("repository", {}).get("full_name", ""),
                            "html_url": item.get("html_url", "")
                        }
                    elif search_type == "repositories":
                        result = {
                            "name": item.get("name", ""),
                            "full_name": item.get("full_name", ""),
                            "description": item.get("description", ""),
                            "html_url": item.get("html_url", ""),
                            "stars": item.get("stargazers_count", 0),
                            "language": item.get("language", "")
                        }
                    else:  # issues
                        result = {
                            "title": item.get("title", ""),
                            "html_url": item.get("html_url", ""),
                            "state": item.get("state", ""),
                            "labels": [label.get("name", "") for label in item.get("labels", [])]
                        }
                    
                    results.append(result)
                
                return ToolResult(
                    success=True,
                    data={
                        "query": query,
                        "search_type": search_type,
                        "total_count": data.get("total_count", 0),
                        "results": results
                    }
                )
            else:
                return ToolResult(
                    success=False,
                    error="未找到搜索结果"
                )
                
        except requests.exceptions.RequestException as e:
            return ToolResult(
                success=False,
                error=f"API请求失败: {str(e)}"
            )
        except Exception as e:
            return ToolResult(
                success=False,
                error=str(e)
            )
    
    def get_schema(self) -> Dict[str, Any]:
        """获取工具调用模式"""
        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "搜索查询关键词"
                        },
                        "search_type": {
                            "type": "string",
                            "enum": ["code", "repositories", "issues"],
                            "description": "搜索类型"
                        }
                    },
                    "required": ["query"]
                }
            }
        }
